package cn.deng.middleware.dynamic.thread.pool.sdk.domain;


import cn.deng.middleware.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolConfigEntity;
import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: DengJingWen deng
 * @description: 动态线程池服务
 * @create: 2025-05-05
 */
public class DynamicThreadPoolService implements IDynamicThreadPoolService{

    private final Logger logger = LoggerFactory.getLogger(DynamicThreadPoolService.class);

    private final Map<String, ThreadPoolExecutor> threadPoolExecutorMap;
    private final String applicationName;

    public DynamicThreadPoolService(String applicationName, Map<String, ThreadPoolExecutor> threadPoolExecutorMap) {
        this.applicationName = applicationName;
        this.threadPoolExecutorMap = threadPoolExecutorMap;
    }

    @Override
    public List<ThreadPoolConfigEntity> queryThreadPoolList() {
        Set<String> threadPoolNames = threadPoolExecutorMap.keySet();
        if (threadPoolNames != null && !threadPoolNames.isEmpty()) {
            List<ThreadPoolConfigEntity> threadPoolConfigEntities = new ArrayList<>();
            for (String threadPoolName : threadPoolNames) {
                ThreadPoolExecutor threadPoolExecutor = threadPoolExecutorMap.get(threadPoolName);
                ThreadPoolConfigEntity threadPoolConfigEntity = this.buildThreadPoolConfigEntity(threadPoolName, threadPoolExecutor);
                threadPoolConfigEntities.add(threadPoolConfigEntity);
            }
            return threadPoolConfigEntities;
        }
        return Collections.emptyList();
    }

    @Override
    public ThreadPoolConfigEntity queryThreadPoolConfigByName(String threadPoolName) {
        ThreadPoolExecutor threadPoolExecutor = threadPoolExecutorMap.get(threadPoolName);
        if (null == threadPoolExecutor){ return new ThreadPoolConfigEntity(applicationName, threadPoolName);}

        // 线程池配置数据
        ThreadPoolConfigEntity threadPoolConfigEntity = this.buildThreadPoolConfigEntity(threadPoolName, threadPoolExecutor);

        if(logger.isDebugEnabled()){
            logger.info("动态线程池，配置查询 应用名：{} 线程名：{} 池化配置：{}", applicationName, threadPoolName, JSON.toJSONString(threadPoolConfigEntity));
        }

        return threadPoolConfigEntity;
    }

    @Override
    public void updateThreadPoolConfig(ThreadPoolConfigEntity threadPoolConfigEntity) {
        if (null == threadPoolConfigEntity || !applicationName.equals(threadPoolConfigEntity.getAppName())){ return;}
        ThreadPoolExecutor threadPoolExecutor = threadPoolExecutorMap.get(threadPoolConfigEntity.getThreadPoolName());
        if (null == threadPoolExecutor){ return;}

        // 更新线程池配置
        threadPoolExecutor.setCorePoolSize(threadPoolConfigEntity.getCorePoolSize());
        threadPoolExecutor.setMaximumPoolSize(threadPoolConfigEntity.getMaximumPoolSize());
    }

    private ThreadPoolConfigEntity buildThreadPoolConfigEntity(String threadPoolName, ThreadPoolExecutor threadPoolExecutor){
        ThreadPoolConfigEntity threadPoolConfigEntity = new ThreadPoolConfigEntity(applicationName, threadPoolName);
        threadPoolConfigEntity.setCorePoolSize(threadPoolExecutor.getCorePoolSize());
        threadPoolConfigEntity.setMaximumPoolSize(threadPoolExecutor.getMaximumPoolSize());
        threadPoolConfigEntity.setActiveCount(threadPoolExecutor.getActiveCount());
        threadPoolConfigEntity.setPoolSize(threadPoolExecutor.getPoolSize());
        threadPoolConfigEntity.setQueueType(threadPoolExecutor.getQueue().getClass().getName());
        threadPoolConfigEntity.setQueueSize(threadPoolExecutor.getQueue().size());
        threadPoolConfigEntity.setRemainingCapacity(threadPoolExecutor.getQueue().remainingCapacity());
        return threadPoolConfigEntity;
    }
}
